import {Component, OnInit} from '@angular/core';
import {DataSource} from "../data-source";
import {FormBuilder, FormGroup, Validators} from "@angular/forms";
import {ActivatedRoute, Router} from "@angular/router";
import {PageSubject} from "../../../../util/page-subject";
import {DataSourceService} from "../data-source.service";
import {DataDictionaryService} from "../../../../services/dataDictionary.service";
import {OneDialogService} from "../../../../widgets/one-dialog/one-dialog.service";
import {ResponseUtil} from "../../../../util/response-util";
import {Path} from "../../../../portal/admin/admin-breadcrumb/breadcrumb";
import {MsgResult} from "../../../../models/msg-result";
import {MsgConstants} from "../../../../constants/constants";

@Component({
  selector: 'app-data-source-update',
  templateUrl: './data-source-update.component.html',
  styleUrls: ['./data-source-update.component.css']
})
export class DataSourceUpdateComponent implements OnInit {

//声明实例
  dataSource: DataSource;

  dataSourcesForm: FormGroup;

  types;
  dataFromSrcs;

  constructor(private router: Router,
              private route: ActivatedRoute,
              private pageSubject: PageSubject,
              private dataSourceService: DataSourceService,
              private dataDictionarysService: DataDictionaryService,
              private dialogService: OneDialogService,
              private responseUtil: ResponseUtil,
              private fb: FormBuilder,) {
    this.initObject();
  }


  ngOnInit() {
    //初始化表单
    this.initUpdateFrom();
    this.pushPage();
    this.initType();
    this.initDataFromSrc();
  }

  /**
   * 面包屑导航
   */
  pushPage() {
    let path = new Path("模板引擎", "");
    this.pageSubject.pushPage("数据源管理", "修改", path);

  }

  /**
   * 获取所有的数据源类型
   */
  initType() {
    this.dataDictionarysService.getChildDicByCode('ZMBLX').subscribe(
      result => this.responseUtil.success(result, this.processTypeResult),
      message => this.responseUtil.error(message)
    );
  }

  /**
   *  获取所有类型
   * @param json
   */
  private processTypeResult = (result: MsgResult) => {
    // console.log(result);
    if (result && result.code == MsgConstants.MSG_CODE_OK) {
      this.types = result.data;
    }
    if (result && result.code != MsgConstants.MSG_CODE_OK) {
      this.dialogService.info(result.message);
    }
  }

  /**
   * 获取所有的数据源类型
   */
  initDataFromSrc() {
    this.dataDictionarysService.getChildDicByCode('SJYLYLX').subscribe(
      result => this.responseUtil.success(result, this.processDataFromSrcResult),
      message => this.responseUtil.error(message)
    );
  }

  /**
   *  获取所有来源
   * @param json
   */
  private processDataFromSrcResult = (result: MsgResult) => {
    // console.log(result);
    if (result && result.code == MsgConstants.MSG_CODE_OK) {
      this.dataFromSrcs = result.data;
    }
    if (result && result.code != MsgConstants.MSG_CODE_OK) {
      this.dialogService.info(result.message);
    }
  }

  //修改信息
  onSubmit() {
    this.dataSourceService.updateDataSource(this.dataSourcesForm.value).subscribe(
      result => this.responseUtil.success(result, this.processUpdateResult),
      message => this.responseUtil.error(message)
    );
  }

  /**
   * 修改成功后调用
   * @param json
   */
  private processUpdateResult = (result: MsgResult) => {
    if (result && result.code == MsgConstants.MSG_CODE_OK) {
      this.dialogService.success(result.message, () => this.cancelDataSourceUpdate());
    }
    if (result && result.code != MsgConstants.MSG_CODE_OK) {
      this.dialogService.info(result.message);
    }
  }

  //取消修改
  cancelDataSourceUpdate() {
    this.router.navigate(['..'], {relativeTo: this.route});
  }

  /**
   * 实例化对象
   */
  private initObject() {
    this.dataSource = new DataSource("", "", "", "", 1, "", "", "", "0");
    this.buildForm();
  }

  /**
   * 构造表单
   */
  buildForm(): void {
    this.dataSourcesForm = this.fb.group({
      'id': [this.dataSource.id],
      'name': [this.dataSource.name, [
        Validators.required
      ]],
      'type': [this.dataSource.type],
      'dataFromSrc': [this.dataSource.dataFromSrc],
      'url': [this.dataSource.url, [
        Validators.required
      ]],
      'description': [this.dataSource.description, [
        Validators.required
      ]],
      'orderBy': [this.dataSource.orderBy, [
        Validators.pattern(/^[1-9]*[1-9][0-9]*$/)
      ]],
      'isUse': [this.dataSource.isUse],
    });

    this.dataSourcesForm.valueChanges.subscribe(
      data => this.onValueChanged(data)
    );
    this.onValueChanged();
  }

  /**
   * 值变化监听
   * @param data
   */
  onValueChanged(data?: any) {
    if (!this.dataSourcesForm) {
      return;
    }
    const form = this.dataSourcesForm;
    for (const field in this.formErrors) {
      this.formErrors[field] = '';
      const control = form.get(field);
      if (control && control.dirty && !control.valid) {
        const messages = this.validationMessages[field];
        for (const key in control.errors) {
          this.formErrors[field] += messages[key] + ' ';
        }
      }
    }
  }

  /**
   * 校验字段
   * @type {{name: string; code: string}}
   */
  formErrors = {
    'name': '',
    'url': '',
    'description': '',
    'orderBy': ''
  };
  /**
   * 校验提示信息
   * @type {{name: {required: string; maxlength: string}; code: {required: string; maxlength: string; pattern: string}}}
   */
  validationMessages = {
    'name': {
      'required': '数据源名称不能为空'
    },
    'url': {
      'required': '数据源URL不能为空'
    },
    'description': {
      'required': '数据源描述不能为空'
    },
    'orderBy': {
      'required': '排序必须为整数'
    }
  };

  /**
   * 通过id查询
   */
  initUpdateFrom() {
    //获取路由参数
    let id = this.route.snapshot.params["id"];
    this.dataSourceService.getDataSourceById(id).subscribe(
      result => this.responseUtil.success(result, this.processGetResult),
      error => this.responseUtil.error(error)
    );
  }

  /**
   * id查询成功后调用
   * @param json
   */
  private processGetResult = (result: MsgResult) => {
    if (result && result.code == MsgConstants.MSG_CODE_OK) {
      this.dataSource = result.data;
      this.dataSourcesForm.patchValue(this.dataSource);
    }
    if (result && result.code != MsgConstants.MSG_CODE_OK) {
      this.dialogService.info(result.message);
    }
  }

}
